package com.tmc.service.intair;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tmc.bean.common.CommonResult;
import com.tmc.bean.common.ContextInfo;
import com.tmc.bean.common.Pagination;
import com.tmc.constant.OrderConstant;
import com.tmc.dao.impl.CommisionPolicyDaoImpl;
import com.tmc.dao.impl.EthClientDaoImpl;
import com.tmc.dao.impl.intair.IntairFareDaoImpl;
import com.tmc.dao.impl.intair.IntairFlightDaoImpl;
import com.tmc.dao.impl.intair.IntairLogDaoImpl;
import com.tmc.dao.impl.intair.IntairOrderDaoImpl;
import com.tmc.dao.impl.intair.IntairPassengerDaoImpl;
import com.tmc.dao.impl.intair.IntairSegmentDaoImpl;
import com.tmc.entity.baseinfo.Airport;
import com.tmc.entity.common.EthClient;
import com.tmc.entity.intair.CommisionPolicy;
import com.tmc.entity.intair.IntairFare;
import com.tmc.entity.intair.IntairFlight;
import com.tmc.entity.intair.IntairLog;
import com.tmc.entity.intair.IntairOrder;
import com.tmc.entity.intair.IntairPassenger;
import com.tmc.entity.intair.IntairSegment;
import com.tmc.service.baseinfo.AirlineServiceImpl;
import com.tmc.service.baseinfo.AirportServiceImpl;
import com.tmc.service.baseinfo.CityServiceImpl;
import com.tmc.service.baseinfo.CountryServiceImpl;
import com.tmc.util.DateUtil;
import com.tmc.util.ObjectUtil;
import com.tmc.util.OrderUtil;

@Service
@Transactional
public class IntairOrderServiceImpl {

	private Log logger = LogFactory.getLog(this.getClass());

	@Autowired
	private IntairOrderDaoImpl orderDao;

	@Autowired
	private IntairFlightDaoImpl flightDao;

	@Autowired
	private IntairSegmentDaoImpl segmentDao;

	@Autowired
	private IntairPassengerDaoImpl passengerDao;

	@Autowired
	private CommisionPolicyDaoImpl policyDao;

	@Autowired
	private IntairFareDaoImpl fareDao;

	@Autowired
	private AirportServiceImpl airportService;

	@Autowired
	private CityServiceImpl cityService;

	@Autowired
	private AirlineServiceImpl airlineService;

	@Autowired
	private EthClientDaoImpl clientDao;

	@Autowired
	private CountryServiceImpl countryService;

	@Autowired
	private CommisionPolicyServiceImpl policyService;

	@Autowired
	private IntairLogDaoImpl logDao;

	public Pagination<IntairOrder> findByCon(ContextInfo context, IntairOrder cond, int pageIndex, int pageSize) {
		Pagination<IntairOrder> result = orderDao.findByCon(context, cond, pageIndex, pageSize);
		this.setOrderExtInfo(result);
		return result;
	}
	
	public List<IntairOrder> findByYesterday(ContextInfo context) {
		//得到昨天的所有订单
		List<IntairOrder> result = orderDao.findByYesterday(context);
		this.setOrderRelateInfo(context, result);
		this.setOrderExtInfo(result);
		return result;
	}
	
	public IntairOrder getById(ContextInfo context, Long orderId) {
		IntairOrder result = orderDao.getById(orderId);
		this.setOrderRelateInfo(context, result);
		this.setOrderExtInfo(result);
		return result;
	}

	private void setOrderExtInfo(Pagination<IntairOrder> result) {
		if (result == null || result.getItems() == null || result.getItems().isEmpty()) {
			return;
		}
		for (IntairOrder order : result.getItems()) {
			this.setOrderExtInfo(order);
		}
	}
	
	private void setOrderExtInfo(List<IntairOrder> result) {
		if (result == null || result.isEmpty()) {
			return;
		}
		for (IntairOrder order : result) {
			this.setOrderExtInfo(order);
		}
	}
	
	private void setOrderExtInfo(IntairOrder result) {
		if (result == null) {
			return;
		}
		result.setOrderStatusName(OrderUtil.getOrderStatusName(result.getOrderStatus()));
		result.setPlatformName(OrderUtil.getPlatformName(result.getPlatform()));
		result.setTicketingTypeName(OrderUtil.getTicketingTypeName(result.getTicketingType()));
		try {
			if (result.getBookDate() != null && result.getBookDate() != 0) {
				result.setBookDateStr(DateUtil.toStrDate(result.getBookDate(), "yyyy-MM-dd"));
			}
			if (result.getDepartureDate() != null && result.getDepartureDate() != 0) {
				result.setDepartureDateStr(DateUtil.toStrDate(result.getDepartureDate(), "yyyy-MM-dd"));
			}
			if (result.getCreationDate() != null && result.getCreationDate() != 0) {
				result.setCreationDateStr(DateUtil.toStrDate(result.getCreationDate(), "yyyy-MM-dd HH:mm:ss"));
			}
			if (result.getPassengers() != null) {
				for (IntairPassenger passenger : result.getPassengers()) {
					if (ObjectUtil.hasText(passenger.getCardDate())) {
						passenger.setCardDateStr(DateUtil
								.toStrDate(DateUtil.toLongDate(passenger.getCardDate(), "yyyy-MM-dd"), "yyyy-MM-dd"));
					}
					passenger.setPassengerTypeName(OrderUtil.getPassengerTypeName(passenger.getPassengerType()));
					passenger.setCardTypeName(OrderUtil.getCardTypeName(passenger.getCardType()));
					passenger.setGenderName(OrderUtil.getGenderName(passenger.getGender()));
				}
			}
			if(result.getLogs() !=null){
				for (IntairLog log : result.getLogs()) {
					if (log.getCreationDate() != null && log.getCreationDate() != 0) {
						log.setCreationDateStr(DateUtil.toStrDate(log.getCreationDate(), "yyyy-MM-dd HH:mm:ss"));
					}
				}
				
			}
		} catch (Exception e) {
			logger.error("日期转换出错！", e);
		}
		if (OrderConstant.PLATFORM_CTRIP.equals(result.getPlatform())) {
			switch (result.getPlatformStatus()) {
			case "1":
				result.setStatusName("未出票");
				break;
			case "2":
				result.setStatusName("出票失败");
				break;
			case "3":
				result.setStatusName("已出票");
				break;
			case "4":
				result.setStatusName("已取消");
				break;
			case "5":
				result.setStatusName("已作废");
				break;
			case "6":
				result.setStatusName("已入库");
				break;
			case "7":
				result.setStatusName("已支付");
				break;
			case "8":
				result.setStatusName("验证中");
				break;
			}
		}
	}
	
	private void setOrderRelateInfo(ContextInfo context, List<IntairOrder> result) {
		if(result == null || result.isEmpty()){
			return;
		}
		for (IntairOrder order : result) {
			this.setOrderRelateInfo(context, order);
		}
		
	}
	
	private void setOrderRelateInfo(ContextInfo context, IntairOrder result) {
		// 给订单设置航段信息
		List<IntairFlight> flightlist = flightDao.findByOrderId(context, result.getOrderId());
		if (flightlist != null) {
			result.setFlights(flightlist);
			for (IntairFlight flight : flightlist) {
				List<IntairSegment> segmentList = segmentDao.findByFlightId(context, flight.getFlightId());
				if (segmentList != null) {
					flight.setSegments(segmentList);
				}
				flight.setTransferCityName(cityService.getNameByCode(context, flight.getTransfer()));
			}
		}
		// 给订单设置乘客信息
		List<IntairPassenger> passengerList = passengerDao.findByOrderId(context, result.getOrderId());
		if (passengerList != null) {
			result.setPassengers(passengerList);
			for (IntairPassenger passenger : passengerList) {
				IntairFare fare = fareDao.findByPassengerId(context, passenger.getPassengerId());
				if (fare != null) {
					passenger.setFare(fare);
				}
			}
		}
		// 给订单设置政策信息
		
		List<CommisionPolicy> dbPolicys = null;
		// 注意 !result.getCommisionPolicyId().equals("null")
		if (ObjectUtil.hasText(result.getCommisionPolicyId())) {
			String[] strings = result.getCommisionPolicyId().split(",");
			dbPolicys = new ArrayList<CommisionPolicy>();
			for (String string : strings) {
				CommisionPolicy policy = policyDao.getById(Long.valueOf(string));
				dbPolicys.add(policy);
			}
		}
		CommisionPolicy commisionPolicy = policyService.calculatePriceInfo(dbPolicys);
		//policyService.calculateCommisionByDbPolicy(commisionPolicy, dbPolicys);// 设置计算价格信息等
		policyService.beforeShow(dbPolicys);// 格式化时间
		result.setCommisionPolicy(commisionPolicy);
		result.setPolicys(dbPolicys);

		// 给订单设置日志信息
		List<IntairLog> logList = logDao.findByOrderId(context, result.getOrderId());
		if (logList != null) {
			result.setLogs(logList);
		}
	}

	public Map<String, Object> beforeShowPassenger(List<IntairPassenger> list) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> passengerTypes = new HashMap<String, Object>();
		// List<String> passengerTypes=new ArrayList<String>();
		if (list == null) {
			return null;
		}
		List<String> adultNames = new ArrayList<String>();
		List<String> childNames = new ArrayList<String>();
		List<String> infantNames = new ArrayList<String>();
		List<String> otherNames = new ArrayList<String>();// 乘客信息不全 只有名字的情况
		Integer adultCount = 0;
		Integer childCount = 0;
		Integer infantCount = 0;
		Integer otherCount = 0;// 乘客信息不全 只有名字的情况
		IntairFare adultFare = null;
		IntairFare childFare = null;
		IntairFare infantFare = null;
		IntairFare otherFare = null;// 乘客信息不全 只有名字的情况
		for (IntairPassenger passenger : list) {
			if (ObjectUtil.noText(passenger.getPassengerType())
					|| !"ADT,CHD,INF".contains(passenger.getPassengerType())) {
				passengerTypes.put("OTHER", "OTHER");
			} else {
				passengerTypes.put(passenger.getPassengerType(), passenger.getPassengerType());
			}

			if (passenger.getPassengerType() != null
					&& passenger.getPassengerType().equals(OrderConstant.PASSENGER_TYPE_ADT)) {
				adultNames.add(passenger.getPassengerNameEn());
				if (adultFare == null) {
					adultFare = passenger.getFare();
				}
				adultCount++;
				continue;
			}
			if (passenger.getPassengerType() != null
					&& passenger.getPassengerType().equals(OrderConstant.PASSENGER_TYPE_CHD)) {
				childNames.add(passenger.getPassengerNameEn());
				childCount++;
				if (childFare == null) {
					childFare = passenger.getFare();
				}
				continue;
			}
			if (passenger.getPassengerType() != null
					&& passenger.getPassengerType().equals(OrderConstant.PASSENGER_TYPE_INF)) {
				infantNames.add(passenger.getPassengerNameEn());
				if (infantFare == null) {
					infantFare = passenger.getFare();
				}
				infantCount++;
				continue;
			}
			if (ObjectUtil.noText(passenger.getPassengerType())) {
				otherNames.add(passenger.getPassengerNameEn());
				if (otherFare == null) {
					otherFare = passenger.getFare();
				}
				otherCount++;
				continue;
			}
		}
		map.put("passengerTypes", passengerTypes);
		map.put("adultNames", adultNames);
		map.put("childNames", childNames);
		map.put("infantNames", infantNames);
		map.put("otherNames", otherNames);
		map.put("adultCount", adultCount);
		map.put("childCount", childCount);
		map.put("infantCount", infantCount);
		map.put("otherCount", otherCount);
		map.put("infantFare", infantFare);
		map.put("childFare", childFare);
		map.put("adultFare", adultFare);
		map.put("otherFare", otherFare);
		return map;
	}

	public CommonResult save(ContextInfo context, IntairOrder order) {
		CommonResult check = this.check(context, order);
		if (!check.isSuccess()) {
			return check;
		}
		IntairOrder dbOrder = null;
		if (order.getOrderId() != null) {
			dbOrder = orderDao.getById(order.getOrderId());
		} else if (ObjectUtil.hasText(order.getPlatform()) && ObjectUtil.hasText(order.getPlatformOrderNum())) {
			dbOrder = orderDao.getByPlatformOrderNum(context, order.getPlatform(), order.getPlatformOrderNum());
		}
		if (dbOrder == null) {
			// 保存之前先处理字段中的数据
			beforeSave(order);
			CommonResult checkRepeat = this.checkRepeat(context, order);
			if (!checkRepeat.isSuccess()) {
				return checkRepeat;
			}
			order.setOrderNum(this.getOrderNum(context, order.getCreationDate()));
			ObjectUtil.setBaseInfo(order, context);
			orderDao.insert(order);
			if (order.getFlights() != null) {
				this.saveFlights(context, order);
			}
			if (order.getPassengers() != null) {
				this.savePassengers(context, order);
			}
			// 更新日志
			if (order.getLog() != null) {
				this.saveLog(context, order);
			}
		} else {
			try {
				ObjectUtil.copyProperties(order, dbOrder, new String[] { "createdBy", "creationDate", "orderId",
						"enabledFlag", "orderNum", "clientId", "vendorId" });
			} catch (Exception e) {
				logger.error("拷贝对象错误", e);
			}
			ObjectUtil.updateBaseInfo(dbOrder, context);
			// TODO 更新航程及乘机人
			orderDao.update(dbOrder);
			// 更新日志
			if (dbOrder.getLog() != null) {
				this.saveLog(context, dbOrder);
			}

		}
		return CommonResult.makeSuccess("保存成功", order.getOrderNum());
	}

	/**
	 * pnr创单的保存
	 * 
	 * @param context
	 * @param order
	 * @return
	 */
	public CommonResult saveByPnr(ContextInfo context, IntairOrder order) {
		CommonResult check = this.check(context, order);
		if (!check.isSuccess()) {
			return check;
		}
		// 保存订单前设置信息
		getOrderStatusAndSource(order);
		beforeSaveByPnr(order);
		beforeSave(order);
		// 设置日志信息
		order.setLog(new IntairLog("pnr创建订单成功", null,
				ObjectUtil.hasText(order.getOrderStatus()) ? order.getOrderStatus() : ""));
		return save(context, order);
	}

	/**
	 * 选择政策
	 * 
	 * @param context
	 * @param orderId
	 * @param policyIds
	 * @return
	 */
	public IntairOrder selectCommision(ContextInfo context, Long orderId, String policyIds) {

		IntairOrder dbOrder = this.getById(context, orderId);// 获取数据库的订单

		// 给订单设置政策信息

		List<CommisionPolicy> policys = new ArrayList<CommisionPolicy>();
		if (ObjectUtil.hasText(policyIds)) {
			String[] strings = policyIds.split(",");
			for (String string : strings) {
				CommisionPolicy policy = policyDao.getById(Long.valueOf(string));
				policys.add(policy);
			}
		}
		//CommisionPolicy commisionPolicy = new CommisionPolicy();
		//policyService.calculateCommisionByDbPolicy(commisionPolicy, policys);// 设置计算好的价格信息
		CommisionPolicy commisionPolicy = policyService.calculatePriceInfo(policys);
		beforeUpdateFare(commisionPolicy, dbOrder);// 更新订单对应下的fare表中的代理费,后返，开票手续费，

		// TODO 在选择政策时更新fare信息 逻辑可能不合理
		for (IntairPassenger passenger : dbOrder.getPassengers()) {
			if(passenger.getFare() == null){
				continue;
			}
			passenger.getFare().setCommisionPolicyId(policyIds);
			fareDao.update(passenger.getFare());
		}

		dbOrder.setCommisionPolicy(commisionPolicy);
		dbOrder.setPolicys(policys);
		dbOrder.setCommisionPolicyId(policyIds);
		// 设置日志信息
		dbOrder.setLog(
				new IntairLog("选择政策成功", ObjectUtil.hasText(dbOrder.getOrderStatus()) ? dbOrder.getOrderStatus() : "",
						ObjectUtil.hasText(dbOrder.getOrderStatus()) ? dbOrder.getOrderStatus() : ""));
		this.save(context, dbOrder);
		dbOrder = this.getById(context, orderId);
		return dbOrder;
	}

	public void beforeUpdateFare(CommisionPolicy policy, IntairOrder order) {
		String flightType = order.getFlightType().equals(OrderConstant.FLIGHT_TYPE_OW) ? "OW" : "RT";
		for (IntairPassenger passenger : order.getPassengers()) {
			if(passenger.getFare() == null){
				continue;
			}
			IntairFare fare = passenger.getFare();
			// 设置政策号
			fare.setCommisionPolicyId(policy.getPolicyIds());
			// 当乘客类型为空或者为成人的情况
			if (ObjectUtil.noText(passenger.getPassengerType())
					|| passenger.getPassengerType().equals(OrderConstant.PASSENGER_TYPE_ADT)) {
				fare.setCommisionPrice(Math.ceil(policy.getCommision() * fare.getTicketPrice() / 100));
				fare.setReward(Math.ceil(policy.getReward() * fare.getTicketPrice() / 100));
				fare.setTicketingPrice(policy.getTicketingPrice());
				fare.setOff(flightType.equals("OW") ? policy.getOwOff() : policy.getRtOff());
			} else if (passenger.getPassengerType().equals(OrderConstant.PASSENGER_TYPE_CHD)) {
				// 儿童奖励
				fare.setReward(Math.ceil(policy.getChdReward() * fare.getTicketPrice() / 100));
				// 儿童代理费
				fare.setCommisionPrice(Math.ceil(policy.getChdCommision() * fare.getTicketPrice() / 100));
				// 儿童加手开票手续费
				fare.setTicketingPrice(policy.getChdTicketingPrice());
				// 儿童直减
				fare.setOff(flightType.equals("OW") ? policy.getChdOwOff() : policy.getChdRtOff());
			} else if (passenger.getPassengerType().equals(OrderConstant.PASSENGER_TYPE_INF)) {
				// 婴儿奖励
				fare.setReward(Math.ceil(policy.getInfReward()));
				// 婴儿代理费
				fare.setCommisionPrice(Math.ceil(policy.getInfCommision() * fare.getTicketPrice() / 100));
				// 婴儿加手开票手续费
				fare.setTicketingPrice(policy.getInfTicketingPrice());
				// 婴儿直减
				fare.setOff(flightType.equals("OW") ? policy.getInfOwOff() : policy.getInfRtOff());
			}
		}
	}

	/**
	 * 根据segment表里的status字段是否存在'K'来判断状态
	 * 
	 * @param order
	 */
	public void getOrderStatusAndSource(IntairOrder order) {
		// TODO
		if (order == null || order.getFlights() == null) {
			return;
		}
		Integer segmentStatusflag = 0;// 当该变量值大于1时，表示订座成功，默认值等于0.
		for (IntairFlight flight : order.getFlights()) {
			segmentStatusflag = 1;// 当该变量值大于1时，表示订座成功，默认值等于1.
			for (IntairSegment segment : flight.getSegments()) {
				if (segment.getStatus().indexOf("K") < 0) {
					// 订座失败
					segmentStatusflag = -1;
					break;
				}
			}
			if (segmentStatusflag == -1) {
				break;
			} else {
				continue;
			}
		}
		if (segmentStatusflag <= 0) {// 订座失败时，订座中
			order.setOrderStatus(OrderConstant.ORDER_STATUS_BOOKING);
			order.setSource(OrderConstant.OrderSource.SYSTEM.getSource());
		} else {// 订座成功，待审核
			order.setSource(OrderConstant.OrderSource.INTERFACE.getSource());
			order.setOrderStatus(OrderConstant.ORDER_STATUS_CHECKING);
		}
	}

	public void beforeSaveByPnr(IntairOrder order) {
		if (order == null) {
			return;
		}
		//设定订票时间
		if(order.getBookDate() == null){
			order.setBookDate(DateUtil.toLongDate(new Date()));
		}
		// 设置出票方式// 1:自动出票;2:手工出票
		if (order.getTicketingType() == null) {
			order.setTicketingType(2);
		}
		// 设置order表里的platform
		order.setPlatform(OrderConstant.PLATFORM_ZIYING);
		// 设置航程和航段时间信息
		for (IntairFlight flight : order.getFlights()) {
			for (IntairSegment segment : flight.getSegments()) {
				try {
					// 把yyyy-M-d转为yyyy-MM-dd
					if (ObjectUtil.hasText(segment.getDepartureDate())) {
						segment.setDepartureDate(DateUtil
								.toStrDate(DateUtil.toLongDate(segment.getDepartureDate(), "yyyy-M-d"), "yyyy-MM-dd"));
					}
					if (ObjectUtil.hasText(segment.getArrivalDate())) {
						segment.setArrivalDate(DateUtil
								.toStrDate(DateUtil.toLongDate(segment.getArrivalDate(), "yyyy-M-d"), "yyyy-MM-dd"));
					}
					// 把HHmm转为HH:mm格式
					if (ObjectUtil.hasText(segment.getDepartureTime())) {
						segment.setDepartureTime(
								DateUtil.toStrDate(DateUtil.format(segment.getDepartureTime(), "HHmm"), "HH:mm"));
					}
					if (ObjectUtil.hasText(segment.getArrivalTime())) {
						segment.setArrivalTime(
								DateUtil.toStrDate(DateUtil.format(segment.getArrivalTime(), "HHmm"), "HH:mm"));
					}
				} catch (ParseException e) {
					logger.error("时间转换出错", e);
				}
			}
		}
		// 设置乘客信息
		for (IntairPassenger passenger : order.getPassengers()) {
			// 设置国籍
			// passenger.setNationalityName(countryService.getNameByCode(passenger.getNationality()));
			try {
				if (passenger.getBirthday() != null && !passenger.getBirthday().equals("")) {
					// 把生日转为yyyy
					passenger.setBirthday(DateUtil.toStrDate(
							DateUtil.toLongDate(passenger.getBirthday(), DateUtil.yyyy_M_d), DateUtil.yyyy_MM_dd));
				}
				if (passenger.getCardDate() != null && !passenger.getCardDate().equals("")) {
					passenger.setCardDate(DateUtil.toStrDate(
							DateUtil.toLongDate(passenger.getCardDate(), DateUtil.yyyy_M_d), DateUtil.yyyy_MM_dd));
				}
			} catch (ParseException e) {
				logger.error("日期转换出错！", e);
			}
		}
	}

	/**
	 * 保存订单前给订单设置信息
	 * 
	 * @param order
	 */
	public void beforeSave(IntairOrder order) {
		// 以下两个变量和order表的字段对应
		StringBuffer flightNo = new StringBuffer();
		StringBuffer passengerNames = new StringBuffer();
		if (order.getFlights() != null && order.getFlights().size() > 0) {
			for (int flightFlag = 0; flightFlag < order.getFlights().size(); flightFlag++) {
				IntairFlight flight = order.getFlights().get(flightFlag);
				if (flight.getSegments() != null && flight.getSegments().size() > 0) {
					for (int segmentFlag = 0; segmentFlag < flight.getSegments().size(); segmentFlag++) {
						IntairSegment segment = flight.getSegments().get(segmentFlag);
						// 设置flight中转信息
						if (segmentFlag >= 1) {
							flight.setTransferType(OrderConstant.TRANSFER_TYPE_TRANSFER);
							flight.setTransfer(segment.getDeparture());

							// TODO 中转多次的情况
						}
						// 设置order表中的航班号
						if ((flightFlag >= order.getFlights().size() - 1)
								&& (segmentFlag >= flight.getSegments().size() - 1)) {
							flightNo.append(segment.getAirline() + segment.getFlightNo());
						} else {
							flightNo.append(segment.getAirline() + segment.getFlightNo() + "/");
						}

						Airport dptAirport = airportService.getByCode(segment.getDeparture());
						if (dptAirport != null) {
							segment.setDepartureName(dptAirport.getAirportName());
							segment.setDepartureCity(dptAirport.getCityCode());
							segment.setDepartureCityName(dptAirport.getCityName());

						}
						Airport avlAirport = airportService.getByCode(segment.getArrival());
						if (avlAirport != null) {
							segment.setArrivalName(avlAirport.getAirportName());
							segment.setArrivalCity(avlAirport.getCityCode());
							segment.setArrivalCityName(avlAirport.getCityName());
						}
						segment.setAirlineName(airlineService.getNameByCode(segment.getAirline()));
					}
				}
				// 设置flight信息
				IntairSegment firstSegment = flight.getSegments().get(0);
				IntairSegment lastSegment = flight.getSegments().get(flight.getSegments().size() - 1);
				flight.setDepartureDate(firstSegment.getDepartureDate());
				flight.setDepartureTime(firstSegment.getDepartureTime());
				flight.setDepartureName(firstSegment.getDepartureName());
				flight.setDepartureCity(firstSegment.getDepartureCity());
				flight.setDepartureCityName(firstSegment.getDepartureCityName());
				flight.setArrivalDate(lastSegment.getDepartureDate());
				flight.setArrivalTime(lastSegment.getArrivalTime());
				flight.setArrivalName(lastSegment.getArrivalName());
				flight.setArrivalCity(lastSegment.getArrivalCity());
				flight.setArrivalCityName(lastSegment.getArrivalCityName());

				flight.setAirlineName(airlineService.getNameByCode(flight.getAirline()));

			}

			// 根据航程数设置flightType
			if (order.getFlights().size() == 1) { // 单程
				order.setFlightType(OrderConstant.FLIGHT_TYPE_OW);

			} else if (order.getFlights().size() == 2 && order.getFlights().get(0).getDepartureCity()
					.equals(order.getFlights().get(1).getArrivalCity())) {
				order.setFlightType(OrderConstant.FLIGHT_TYPE_RT);// 往返
			} else if (order.getFlights().get(0).getDepartureCity()
					.equals(order.getFlights().get(order.getFlights().size() - 1).getArrivalCity())) {
				// 连程
				order.setFlightType(OrderConstant.FLIGHT_TYPE_UN);
			} else {
				// 多程
				order.setFlightType(OrderConstant.FLIGHT_TYPE_MU);
			}

			// 设置order信息
			IntairFlight firstFlight = order.getFlights().get(0);
			IntairFlight lastFlight = order.getFlights().get(order.getFlights().size() - 1);
			// 设置order的airline 此处存在问题！
			order.setAirline(firstFlight.getAirline());
			order.setDeparture(firstFlight.getDeparture());
			order.setDepartureCity(firstFlight.getDepartureCity());
			order.setDepartureCityName(firstFlight.getDepartureCityName());
			if (OrderConstant.FLIGHT_TYPE_RT.equals(order.getFlightType())) {
				order.setArrival(firstFlight.getArrival());
				order.setArrivalCity(firstFlight.getArrivalCity());
				order.setArrivalCityName(firstFlight.getArrivalCityName());
			} else {
				order.setArrival(lastFlight.getArrival());
				order.setArrivalCity(lastFlight.getArrivalCity());
				order.setArrivalCityName(lastFlight.getArrivalCityName());
			}
			order.setDepartureDate(DateUtil.toLongDate(
					firstFlight.getDepartureDate() + " " + firstFlight.getDepartureTime(), "yyyy-MM-dd HH:mm"));
			order.setArrivalDate(DateUtil.toLongDate(lastFlight.getDepartureDate() + " " + lastFlight.getArrivalTime(),
					"yyyy-MM-dd HH:mm"));
		}
		// 设置出票方式// 1:自动出票;2:手工出票
		if (order.getTicketingType() == null) {
			order.setTicketingType(2);
		}
		// 设置order表里的platform
		if (ObjectUtil.hasText(order.getPlatform())) {
			order.setPlatform(OrderConstant.PLATFORM_ZIYING);
		}
		// 设置order表里的航班号
		order.setFlightNo(flightNo.toString());
		// 设置总价
		order.setTotalAmount(order.getTotalAmount() == null ? 0D : order.getTotalAmount());
		// 设置所有乘客的姓名集
		for (int passengerFlag = 0; passengerFlag < order.getPassengers().size(); passengerFlag++) {
			// 设置国籍名字
			IntairPassenger passenger = order.getPassengers().get(passengerFlag);
			passenger.setFare(order.getFare());// 给乘客设置fare信息
			passenger.setNationalityName(countryService.getNameByCode(passenger.getNationality()));
			if (ObjectUtil.noText(passenger.getPassengerNameEn())) {
				passenger.setPassengerNameEn(passenger.getFirstName() + "/" + passenger.getLastName());
			}
			if (passengerFlag < (order.getPassengers().size() - 1)) {
				passengerNames.append(passenger.getPassengerNameEn() + ",");
			} else {
				passengerNames.append(passenger.getPassengerNameEn());
			}
		}
		order.setPassengerNames(passengerNames.toString());
	}

	// public void beforeSaveFLight(List<IntairFlight> flights){
	// for (IntairFlight flight : flights) {
	// for (IntairSegment segment : flight.getSegments()) {
	//
	// }
	// }
	// }
	// public void beforeSaveSegment(List<IntairSegment> segments){
	// for (IntairSegment segment : segments) {
	//
	// }
	// }
	// public void beforeSavePassenger(List<IntairPassenger> passengers){
	// for (IntairPassenger passenger : passengers) {
	//
	// }
	// }

	/**
	 * 订单审核通过的
	 * 
	 * @author
	 * @return
	 */
	public CommonResult orderChecked(ContextInfo context, Long orderId, String policyIds) {
		IntairOrder dborder = this.getById(new ContextInfo(), orderId);
		if (dborder == null) {
			return CommonResult.makeFail("审核时出错！");
		}
		this.beforeChecked(dborder);
		return this.updateOrderStatus(context, dborder, "订单审核成功");
	}

	/**
	 * 为审核通过前设置订单状态。
	 * 
	 * @param order
	 */
	public void beforeChecked(IntairOrder order) {
		if (order.getClientId() != null) { // 属于商旅客户
			EthClient dbclient = clientDao.getById(order.getClientId());
			if (dbclient != null && !dbclient.getSettleMethod().equals("日结") && dbclient.getCreditBalance() != null
					&& dbclient.getCreditBalance() >= order.getTotalAmount()) {
				order.setOrderStatus(OrderConstant.ORDER_STATUS_TICKETING);// 出票中
				// TODO 更新客户的余额
				dbclient.setCreditBalance(dbclient.getCreditAvailable() - order.getTotalAmount());
				ObjectUtil.updateBaseInfo(dbclient, new ContextInfo());
				clientDao.update(dbclient);
			} else {// 客户的可用余额不足
				order.setOrderStatus(OrderConstant.ORDER_STATUS_PAYING);// 订单支付中
			}
		} else { // 属于个人订单
			order.setOrderStatus(OrderConstant.ORDER_STATUS_PAYING);// 订单支付中
		}
	}

	public CommonResult updateOrderStatus(ContextInfo context, IntairOrder order, String operation) {
		if (order == null || order.getOrderId() == null) {
			CommonResult.makeFail("审核时出错");
		}
		IntairOrder dbOrder = orderDao.getById(order.getOrderId());
		if (dbOrder == null) {
			return CommonResult.makeFail("");
		}
		// 设置日志信息
		dbOrder.setLog(new IntairLog(operation, dbOrder.getOrderStatus(), order.getOrderStatus()));
		dbOrder.setOrderStatus(order.getOrderStatus());// 设置状态
		this.save(context, dbOrder);
		return CommonResult.makeSuccess();
	}

	private  String getOrderNum(ContextInfo context, Long creationDate) {
		if (creationDate == null) {
			creationDate = DateUtil.toLongDate(new Date());
		}
		String tag = "IA" + (creationDate + "").substring(2, 8);
		IntairOrder newestOrder = orderDao.getNewestOrder(context);
		String orderNum = newestOrder.getOrderNum();
		Long nums = Long.valueOf(orderNum.substring(orderNum.length() - 4, orderNum.length()));
		if (newestOrder.getCreationDate() < DateUtil.toLongDate(new Date(), DateUtil.yyyyMMdd) * 1000000) {
			nums = 0L;
		}
		return tag + this.get4CharacterNo(nums + 1);
	}

	private String get4CharacterNo(Long num) {
		String str = String.valueOf(num);
		for (int i = str.length(); i < 4; i++) {
			str = "0" + str;
		}
		return str;
	}

	public Long getTodayOrdersCount(ContextInfo context, String tag) {
		return orderDao.getTodayOrdersCount(context, tag);
	}

	private void savePassengers(ContextInfo context, IntairOrder order) {
		Double total = 0D;
		String ticketNum = "";
		for (IntairPassenger psg : order.getPassengers()) {
			psg.setOrderId(order.getOrderId());
			ObjectUtil.setBaseInfo(psg, context);
			IntairFare fare = psg.getFare() == null ? order.getFare() : psg.getFare();
			passengerDao.insert(psg);
			if (fare != null) {
				IntairFare fare1 = ObjectUtil.makeTargetBean(fare, IntairFare.class);
				fare1.setPassengerId(psg.getPassengerId());
				fare1.setOrderId(order.getOrderId());
				ObjectUtil.setBaseInfo(fare1, context);
				fareDao.insert(fare1);
				total += fare1.getTotalAmount();
				if (fare1.getTicketNum() != null && ticketNum.indexOf(fare1.getTicketNum()) < 0) {
					ticketNum += fare1.getTicketNum() + "/";
				}
			}
		}
		order.setTotalAmount(total);
		if (ObjectUtil.hasText(ticketNum)) {
			order.setTicketNum(ticketNum.substring(0, ticketNum.length() - 1));
		}
	}

	private void saveFlights(ContextInfo context, IntairOrder order) {
		for (IntairFlight flight : order.getFlights()) {
			flight.setOrderId(order.getOrderId());
			ObjectUtil.setBaseInfo(flight, context);
			flightDao.insert(flight);
			for (IntairSegment segment : flight.getSegments()) {
				segment.setFlightId(flight.getFlightId());
				ObjectUtil.setBaseInfo(segment, context);
				segmentDao.insert(segment);
			}
		}
	}

	private void saveLog(ContextInfo context, IntairOrder order) {
		if(order == null || order.getLog() == null){
			return;
		}
		IntairLog log = order.getLog();
		log.setOrderId(order.getOrderId());
		ObjectUtil.setBaseInfo(log, context);
		log.setOperatorId(log.getCreatedBy());
		logDao.insert(log);
	}

	@Deprecated
	public List<IntairOrder> findAll() {
		return orderDao.findAll(null);
	}

	@Deprecated
	public List<IntairPassenger> findAllPassengers() {
		return passengerDao.findAll(null);
	}

	@Deprecated
	public List<IntairFare> findAllFares() {
		return fareDao.findAll(null);
	}

	@Deprecated
	public void updateAllPassengers(List<IntairPassenger> passengers) {
		passengerDao.update(passengers);
	}

	public void saveFares(List<IntairFare> mapFs) {
		fareDao.update(mapFs);

	}

	public IntairOrder getCurrent(ContextInfo context) {
		IntairOrder result = orderDao.getCurrent(context);
		this.setOrderExtInfo(result);
		this.setOrderRelateInfo(context, result);
		return result;
	}

	public IntairOrder getByOrderNum(ContextInfo context, String orderNum) {
		return orderDao.getByOrderNum(context, orderNum);
	}

	public IntairOrder getByPlatformOrderNum(ContextInfo context, String platform, String orderNum) {
		return orderDao.getByPlatformOrderNum(context, platform, orderNum);
	}

	private CommonResult checkRepeat(ContextInfo context, IntairOrder order) {
		// 判断重复下单
		IntairOrder newest = orderDao.getNewestOrder(context);
		if (newest == null) {
			return CommonResult.makeSuccess();
		}
		if (newest.getDepartureCity().equals(order.getDepartureCity())
				&& newest.getArrivalCity().equals(order.getArrivalCity())
				&& newest.getDepartureDate().equals(order.getDepartureDate())
				&& newest.getPassengerNames().equals(order.getPassengerNames())) {
			return CommonResult.makeFail("请勿重复下单！");
		}
		return CommonResult.makeSuccess();
	}

	private CommonResult check(ContextInfo context, IntairOrder order) {
		// TODO Auto-generated method stub
		return CommonResult.makeSuccess();
	}

	public CommonResult delete(ContextInfo context, Long orderId) {
		// TODO Auto-generated method stub
		return null;
	}

}
